const Koa = require('koa');
const app = new Koa();
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
const port = 8081;
const UserModel = require('./modules/user');
let user = [];

server.listen(process.env.PORT || port, ()=>{
    console.log(`app run at : http://127.0.0.1:${port}`);
})

io.on('connection', function (socket) {
    let isNewPerson = true;
    let username = null;
    /*监听登录*/
    socket.on('login',async (data)=> {
        let isNewPerson = await UserModel.findUserByName(data.username);
        if(isNewPerson == null){
            let username = data.username;
            let password = '';
            let iscreat = await UserModel.create({username,password})
            //login success
            if(iscreat){
                socket.emit('loginSuccess',data);
                //向所有连接客户端广播add事件
                io.sockets.emit('add',data);
            }else{
                socket.emit('loginFail','创建失败');
            }
        }else{
            //login fail
            socket.emit('loginFail','该用户已经登陆');
        }
    })
    socket.on('disconnect',async ()=> {
        /*向所有连接的客户端广播leave事件*/
        io.sockets.emit('leave',username);
        let data = await UserModel.findUserByName(username);
        await UserModel.delete(data.id);
     })
     socket.on('sendMessage',function(data){
        io.sockets.emit('receiveMessage',data)
    })
})
